package top.whysu.rongcloud.api;

import io.rong.models.Result;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import io.rong.models.response.ResponseResult;
import io.rong.util.CommonUtil;
import io.rong.util.GsonUtil;
import io.rong.util.HttpUtil;

import java.net.HttpURLConnection;
import java.net.URLEncoder;

public class Groups {
    private static final String UTF8 = "UTF-8";
    private static final String PATH = "group";
    private String appKey;
    private String appSecret;
    public Bans bans;
    private RongCloudSMS rongCloudSMS;

    public RongCloudSMS getRongCloudSMS() {
        return rongCloudSMS;
    }

    public void setRongCloudSMS(RongCloudSMS rongCloudSMS) {
        this.rongCloudSMS = rongCloudSMS;
    }

    public void setRongCloud(RongCloudSMS rongCloudSMS) {
        this.rongCloudSMS = rongCloudSMS;
        this.bans.setRongCloudSMS(rongCloudSMS);
    }

    public Groups(String appKey, String appSecret) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.bans = new Bans(appKey, appSecret);
        this.bans.setRongCloudSMS(this.rongCloudSMS);
    }

    public Result create(GroupModel group) throws Exception {
        String message = CommonUtil.checkFiled(group, "group", "create");
        if (null != message) {
            return (ResponseResult)GsonUtil.fromJson(message, ResponseResult.class);
        } else {
            StringBuilder sb = new StringBuilder();
            GroupMember[] members = group.getMembers();
            GroupMember[] var5 = members;
            int var6 = members.length;

            for(int var7 = 0; var7 < var6; ++var7) {
                GroupMember member = var5[var7];
                sb.append("&userId=").append(URLEncoder.encode(member.getId().toString(), "UTF-8"));
            }

            sb.append("&groupId=").append(URLEncoder.encode(group.getId().toString(), "UTF-8"));
            sb.append("&groupName=").append(URLEncoder.encode(group.getName().toString(), "UTF-8"));
            String body = sb.toString();
            if (body.indexOf("&") == 0) {
                body = body.substring(1, body.length());
            }

            HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(this.rongCloudSMS.getApiHostType(), this.appKey, this.appSecret, "/group/create.json", "application/x-www-form-urlencoded");
            HttpUtil.setBodyParameter(body, conn);
            return (ResponseResult) GsonUtil.fromJson(CommonUtil.getResponseByCode("group", "create", HttpUtil.returnResult(conn)), ResponseResult.class);
        }
    }
}
